package kogukond;


import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import prefuse.data.Graph;
import prefuse.data.io.GraphMLReader;

public class GetGraphML {
    public static final String DATA_FILE = "/kogukond/data/socialnetdb.xml";

	public Graph getGraphML (String graphSourceURL) {
        Graph graphML = null;

		if (graphSourceURL == "Datafile" ){
				graphML = getGraphMLfromDatafile(DATA_FILE);
		}
		else {
				// call the appropriate method on the rails kogukond controller
	    		graphML = getGraphMLfromURL(graphSourceURL + "/getGraphML");
	    }
		return graphML;
    }

	public Graph getGraphML () {
		return getGraphMLfromDatafile(DATA_FILE);
    }

	public Graph queryGraphML (String sourceURL, String queryCriteria) {
    	String URLwithQuery;
    	// call the index method on the rails kogukond controller with the query criteria
        // TODO: Why do we have to use index in the controller to keep from losing the parameters?
    	URLwithQuery = sourceURL + queryCriteria;
    	return getGraphMLfromURL(URLwithQuery);
	}

	private static Graph getGraphMLfromDatafile(String datafile) {
		Graph g = null;
        try {
            g = new GraphMLReader().readGraph(datafile);
        } catch ( Exception e ) {
            e.printStackTrace();
            System.exit(1);
        }
        return g;
	}

	private static Graph getGraphMLfromURL(String urlConnection)	{
		Graph g = null;
		try
		{
			URLConnection connection = new URL(urlConnection).openConnection();
			// now read in from inputStream
			InputStream inputStream = connection.getInputStream( );
			g = new GraphMLReader().readGraph(inputStream);
			inputStream.close( );
		}
		catch ( Throwable throwable )
		{
			throwable.printStackTrace( );
		}
		return g;
	}
}